package cn.appsys.controller.devuser;

import java.io.File;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import cn.appsys.pojo.AppVersion;
import cn.appsys.pojo.DevUser;
import cn.appsys.service.appversion.VersionService;
import cn.appsys.service.devuser.AppInfoService;
import cn.appsys.tools.Constants;
import cn.appsys.tools.FileUploadUtil;

/**
 * 版本信息的控制器
 * 
 * @author 寇超强
 *
 */
@Controller
@RequestMapping(value = "sys/dev/flatform/app")
public class VersionController {
	@Resource
	private VersionService versionService;
	@Resource
	private AppInfoService appInfoService;

	/**
	 * 新增app版本 视图
	 */
	@RequestMapping(value = "/appversionadd")
	public String appVersionadd(@ModelAttribute(value = "appVersion") AppVersion appVersion,
			@RequestParam(value = "id") Integer id, Model model) {
		appVersion.setAppId(id);
		List<AppVersion> version = versionService.getAppVersion(id);
		model.addAttribute("appVersionList", version);
		return "dev/appversionadd";
	}

	/**
	 * 保存版本信息
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "/addversionsave")
	public String addVersionSave(AppVersion appVersion, @RequestParam("appId") Integer appId,
			@RequestParam(value = "a_downloadLink", required = false) MultipartFile attach, HttpServletRequest request)
			throws Exception {
		// 文件上传
		String downLoadLink = request.getContextPath() + File.separator + "statics" + File.separator + "uploadfiles"; // 下载链接
		String apkLocPath = null; // apk文件的服务器存储路径
		String apkFileName = ""; // 上传的apk文件名称
		String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
		// 判断上传的文件是否为空
		if (!attach.isEmpty()) {
			// 获取项目路径

			// 获得原文件名
			String oldFileName = attach.getOriginalFilename();
			System.out.println(oldFileName);
			// 获取原文件后缀
			String prefix = FilenameUtils.getExtension(oldFileName);
			System.out.println(prefix);
			// 指定上传文件的大小
			int fileSize = 5000000;
			if (attach.getSize() > fileSize) {
				request.setAttribute("fileUploadError", "上传文件大小不能超过500kb");
				return "appversionadd";
			} else if (prefix.equalsIgnoreCase("apk")) {
				apkFileName += appInfoService.getAppInfobyId(appId).getAPKName() + "-" + appVersion.getVersionNo()
						+ ".apk";
				System.out.println(apkFileName);
			}

			File file = new File(path, apkFileName);
			if (!file.exists()) {
				file.mkdirs();
			}
			// 保存
			try {
				attach.transferTo(file);
			} catch (Exception e) {
				e.printStackTrace();
				request.setAttribute("fileUploadError", "上传文件失败");
			}
			// 判断文件格式
		}
		downLoadLink += File.separator + apkFileName;
		apkLocPath = path + File.separator + apkFileName;
		appVersion.setApkFileName(apkFileName);
		appVersion.setDownloadLink(downLoadLink);
		appVersion.setApkLocPath(apkLocPath);
		appVersion.setCreatedBy(((DevUser) (request.getSession().getAttribute(Constants.DEV_USER_SESSION))).getId());
		appVersion.setCreationDate(new Date());
		if (versionService.addVersion(appVersion, appId)) {

			return "redirect:/sys/dev/flatform/app/list";
		}
		return "redirect:/addversionsave";
	}

	/**
	 * 修改版本视图
	 */
	@RequestMapping(value = "/appversionmodify")
	public String appVersionModify(@RequestParam(value = "vid") Integer vid, @RequestParam(value = "aid") Integer aid,
			Model model) {
		List<AppVersion> appVersionList = versionService.getAppVersion(aid);
		model.addAttribute("appVersionList", appVersionList);
		for (AppVersion appVersion : appVersionList) {
			if (appVersion.getId() == vid)
				model.addAttribute("appVersion", appVersion);
		}
		return "dev/appversionmodify";
	}

	/**
	 * 保存修改后的版本信息
	 */
	@RequestMapping(value = "/appversionmodifysave")
	public String appVersionModifySave( AppVersion appVersion, HttpSession session,
			MultipartFile attach, HttpServletRequest request, @RequestParam("appId") Integer appId) {

		String downLoadLink = request.getContextPath() + File.separator + "statics" + File.separator + "uploadfiles"; // 下载链接
		String apkLocPath = null; // apk文件的服务器存储路径
		String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
		String fileName = appInfoService.getAppInfobyId(appId).getAPKName() + "-" + appVersion.getVersionNo() + ".apk";
		FileUploadUtil fileLoad = new FileUploadUtil(fileName, path, attach, 5000000);
		int falg = fileLoad.upLoadFile();
		if (falg == -1) {
			// 文件过大，上传失败
			request.setAttribute("fileUploadError", Constants.FILEUPLOAD_ERROR_4);
			return "dev/appversionmodify";
		} else if (falg == -2) {
			// 文件格式不正确
			request.setAttribute("fileUploadError", Constants.FILEUPLOAD_ERROR_3);
			return "dev/appversionmodify";
		} else if (falg == -3) {
			// 文件上传失败
			request.setAttribute("fileUploadError", Constants.FILEUPLOAD_ERROR_2);
			return "dev/appversionmodify";
		}
		downLoadLink += File.separator + fileName;
		apkLocPath = path + File.separator + fileName;
		appVersion.setApkFileName(fileName);
		appVersion.setDownloadLink(downLoadLink);
		appVersion.setApkLocPath(apkLocPath);
		appVersion.setModifyBy(((DevUser) (session.getAttribute(Constants.DEV_USER_SESSION))).getId());
		appVersion.setModifyDate(new Date());
		if (versionService.updateVersion(appVersion))
			return "redirect:/sys/dev/flatform/app/list";
		return "dev/appversionmodify";
	}
	/**
	 * 删除文件
	 */

}
